#!/usr/bin/python3
# -*- coding: UTF-8 -*-

from urllib import request
import json
from pymongo import MongoClient

import config

server = config.dbServer
api = config.sinaTagApi
database = config.db
sessionTable = config.editorSessionCollection
userDocsTable = config.filterDocsCollection
testLabel = config.testLabel

client = MongoClient(server)
db = client[database]
editorSessions = db[sessionTable]
userDocs = db[userDocsTable]


def recommend(category):
    if category is None:
        docs = userDocs.find()
    else:
        docs = userDocs.find({'docCategory': category})

    for doc in docs:
        data = json.dumps({"title": doc['title'], "url": "", "content": doc['content'], "category": doc['docCategory']})
        data = bytes(data, 'utf-8')
        req = request.Request(api, data=data, headers={'Content-Type': 'application/json'})
        response = request.urlopen(req).read().decode('utf-8')
        message = json.loads(response)
        # print(message['entity']['sessionID'])
        # print(doc['docCategory'])
        editorSessions.update({"_id": message['entity']['sessionID']},
                              {"$set": {"articleCategory": doc['docCategory'], "testLabel": testLabel}})


if __name__ == '__main__':
    recommend(None)
